2
0

download.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { createRoute, OpenAPIHono, z } from '@hono/zod-openapi';
  2. import { FileService } from '@/server/modules/files/file.service';
  3. import { ErrorSchema } from '@/server/utils/errorHandler';
  4. import { AppDataSource } from '@/server/data-source';
  5. import { AuthContext } from '@/server/types/context';
  6. import { authMiddleware } from '@/server/middleware/auth.middleware';
  7. // 获取文件下载URL路由
  8. const downloadFileRoute = createRoute({
  9. method: 'get',
  10. path: '/{id}/download',
  11. middleware: [authMiddleware],
  12. request: {
  13. params: z.object({
  14. id: z.coerce.number().openapi({
  15. param: { name: 'id', in: 'path' },
  16. example: 1,
  17. description: '文件ID'
  18. })
  19. })
  20. },
  21. responses: {
  22. 200: {
  23. description: '获取文件下载URL成功',
  24. content: {
  25. 'application/json': {
  26. schema: z.object({
  27. url: z.string().url().openapi({
  28. description: '文件下载URL(带Content-Disposition头)',
  29. example: 'https://minio.example.com/bucket/file-key?response-content-disposition=attachment%3B%20filename%3D%22example.jpg%22'
  30. }),
  31. filename: z.string().openapi({
  32. description: '原始文件名',
  33. example: 'example.jpg'
  34. })
  35. })
  36. }
  37. }
  38. },
  39. 404: {
  40. description: '文件不存在',
  41. content: { 'application/json': { schema: ErrorSchema } }
  42. },
  43. 500: {
  44. description: '服务器错误',
  45. content: { 'application/json': { schema: ErrorSchema } }
  46. }
  47. }
  48. });
  49. // 创建文件服务实例
  50. const fileService = new FileService(AppDataSource);
  51. // 创建路由实例
  52. const app = new OpenAPIHono<AuthContext>().openapi(downloadFileRoute, async (c) => {
  53. try {
  54. const { id } = c.req.valid('param');
  55. const result = await fileService.getFileDownloadUrl(id);
  56. return c.json(result, 200);
  57. } catch (error) {
  58. const message = error instanceof Error ? error.message : '获取文件下载URL失败';
  59. const code = (error instanceof Error && error.message === '文件不存在') ? 404 : 500;
  60. return c.json({ code, message }, code);
  61. }
  62. });
  63. export default app;